<template>
  <Layout class="full">
    <Sider hide-trigger :style="{background: '#fff'}" class="mr1 menu" width="280">
      <h3 class="title">
        数据字典
        <ButtonGroup class="fr" size="small">
          <Button>
            <Icon type="md-add" @click="addItem" title="展开/合并" />
          </Button>
          <Button>
            <Icon
              :type="expand?'md-arrow-dropright':'md-arrow-dropdown'"
              @click="toggle"
              title="展开/合并"
            />
          </Button>
          <Button>
            <Icon type="md-refresh" @click="loadTree" title="刷新" />
          </Button>
        </ButtonGroup>
      </h3>
      <div class="tree">
        <Input v-model.trim="keys" search placeholder="请输入名称或编码" clearable />
        <Tree
          :data="projectList"
          @on-select-change="change"
          
          :render="renderContent"
          @on-contextmenu="hadlermenu"
        />
        <template slot="contextMenu">
          <DropdownItem @click.native="editItem">编辑</DropdownItem>
          <DropdownItem @click.native="addItem" style="color: #ed4014">添加</DropdownItem>
        </template>
      </div>
    </Sider>
    <Content class="content">
      <div class="flex p1">
        <div class="fg1">
          <Breadcrumb style="display:inline-block">
            <BreadcrumbItem v-for="(li,i) in names" :key="i">{{li}}</BreadcrumbItem>
          </Breadcrumb>
        </div>

        <div class="fg1 tr">
          <span class="mr20" v-if="node.typeId==2">
            索引：
            <a
              data-clipboard-action="copy"
              :data-clipboard-text="node.code"
              @click="copy"
              id="code"
              class="tag-read"
            >{{node.code}}</a>
          </span>
          <Button type="default" @click="setRoot">返回顶级</Button>
        </div>
      </div>
      <div class="auto">
        <!-- <Dictionary code="system.dictionary.typeId" v-model="code" class="w200"/> {{code}}
        <a @click="code='3'">up</a>-->
        <Table
          border
          :columns="columns"
          :data="data"
          :draggable="edit==-1"
          class="tableCommon"
          @on-drag-drop="onDragDrop"
        >
          <template slot-scope="{ row, index }" slot="typeId">
            <state code="system.dictionary.typeid" type="text" :value="row.typeId"></state>
          </template>
          <template slot-scope="{ row, index }" slot="status">
            <state code="system.dictionary.status" type="tag" :value="row.status"></state>
          </template>
          <template slot-scope="{ row, index }" slot="isStatic">
            <state code="system.dictionary.isStatic" type="tag" :value="row.isStatic"></state>
          </template>
          <template slot-scope="{ row, index }" slot="name">
            <span v-if="edit!=index" v-text="row.name"></span>
            <Input v-else type="text" v-model.trim="cur.name" />
          </template>
          <template slot-scope="{ row, index }" slot="color">
            <div v-if="edit!=index">
              <ColorPicker
                :value="row.color||''"
                transfer
                recommend
                @on-change="setColor($event,row,index)"
              />
            </div>
            <div v-else>
              <ColorPicker v-model="cur.color" transfer recommend />
            </div>
          </template>
          <template slot-scope="{ row, index }" slot="icon">
            <inputIcon v-model="row.icon"  @on-change="setColor($event,row,index)"/>
          </template>
          <template slot-scope="{ row, index }" slot="code">
            <span v-if="edit!=index" v-text="row.code"></span>
            <Input v-else type="text" v-model.trim="cur.code" />
          </template>
          <template slot-scope="{ row, index }" slot="action">
            <div v-if="edit!=index" class="action">
              <op class="edit" @click="editRow(row,index)">编辑</op>
              <op class="remove" @click="delRow(row,index)">删除</op>
            </div>
            <div class="action" v-else>
              <op class="edit" @click="save">保存</op>
              <op class="remove" @click="remove">删除</op>
            </div>
          </template>
        </Table>
        <Button type="primary" :disabled="edit!=-1" long @click="addNew" class="mt2">添加</Button>
        <Alert type="info" class="mt2" v-if="data.length>1&&edit==-1">提示： 支持拖拽排序，数据未保存时不可拖拽排序。</Alert>
      </div>
      <Modal v-model="editModal" :title="editTitle" footer-hide>
        <component :is="detail" :v="editModel" @on-close="editModal=false" @on-ok="editOk" />
      </Modal>
    </Content>
  </Layout>
</template>
<script>
import Edit from "./components/edit";
import api from "./api.js";
import Clipboard from "clipboard";
const root = {
  id: null,
  typeId: -1,
  title: "顶级节点",
  code: "",
  contextmenu: true
};
export default {
  data() {
    return {
      keys: "",
      treeHeight: "",
      code: "2",
      expand: false,
      editModal: false,
      editModel: {
        color: ""
      },
      editTitle: "编辑",
      detail:null,
      node: root,
      color4: "",
      cur: null,
      names: [root.title],
      types: ["系统", "分类", "字典", "字典项"],
      contentData: null,
      addName: "添加",
      tree: [],
      edit: -1,
      data: [],
      columns: [
        {
          type: "index",
          width: 60,
          align: "center"
        },
        {
          title: "类别",
          key: "typeId",
          width: 100,
          align: "center",
          slot: "typeId"
        },
        {
          title: "颜色",
          key: "color",
          width: 100,
          align: "center",
          slot: "color"
        },
        {
          title: "图标",
          key: "icon",
          slot: "icon",
           width: 160,
        },
        {
          title: "名称",
          key: "name",
          width: 150,
          slot: "name"
        },
        {
          title: "编码",
          key: "code",
          slot: "code",
           ellipsis:true
        },
        {
          title: "描述",
          key: "description",
          ellipsis:true
        },
        {
          title: "状态",
          key: "status",
          width: 100,
          align: "center",
          slot: "status"
        },
        {
          title: "锁定",
          key: "isStatic",
          width: 100,
          align: "center",
          slot: "isStatic"
        },
        {
          title: "操作",
          key: "action",
          width: 160,
          align: "center",
          slot: "action"
        }
      ]
    };
  },
  computed: {
    projectList() {
      // let items = this.$u.clone(this.tree);
      let result = [];
      let items = this.tree;
      search(this.keys, items);
      function search(keys, data) {
        data.map(u => {
          if (keys.length == u.title) {
            result.push(u);
          } else {
            let code = "";
            if (u.data && u.data.code) {
              u.data.code.toLowerCase();
              if (keys) {
                keys = keys.toLowerCase();
              }
              code = u.data.code + "";
            }
            if (u.title.indexOf(keys) > -1 || code.indexOf(keys) > -1) {
              result.push(u);
            } else if (u.children) {
              search(keys, u.children);
            }
          }
        });
      }
      return result;
    }
  },
  components: { Edit },
  async fetch({ store, params }) {
    await store.dispatch("loadDictionary"); // 加载数据字典
  },
  created() {
    this.load();
    this.loadTree();
  },
  mounted() {
    window.onresize = () => {
      ///浏览器窗口大小变化
      return (() => {
        window.screenHeight = window.innerHeight;
        this.treeHeight = window.screenHeight - 180;
      })();
    };
  },
  methods: {
    renderContent(h, { root, node, data }) {
      return h(
        "span",
        {
          style: {
            display: "inline-block",
            width: "100%"
          }
        },
        [
          h("state", {
            props: {
              code: "system.dictionary.typeid",
              type: "tag",
              value: data.typeId
            },
            style: {
              float: "left"
            }
          }),
          h("span", data.title)
        ]
      );
    },
    hadlermenu(data) {
      this.contentData = data;
    },
    editItem() {
      this.$Message.info("Click edit of" + this.contextData.title);
    },
    addItem() {
      this.$Message.info("Click edit of" + this.contextData.title);
    },
    copy() {
      var clipboard = new Clipboard(".tag-read");
      clipboard.on("success", e => {
        this.$Message.success("复制成功:" + this.node.code);
        clipboard.destroy();
      });
      clipboard.on("error", e => {
        // 不支持复制
        console.log("该浏览器不支持自动复制"); // 释放内存
        clipboard.destroy();
      });
    },
    editRow(row, index) {
      this.editTitle = "编辑";
      this.editModal = true;
      this.editModel = row;
      this.detail=()=>import("./components/edit")
    },
    toggle() {
      this.expand = !this.expand;
      this.loadTree();
    },
    editOk() {
      this.load();
      this.editModal = false;
      this.detail=null;
    },
    delRow(row, index) {
      var url = `api/Dictionary/Deletes?id=${row.id}`;
      this.$Modal.confirm({
        title: "操作确认",
        content: "确定要删除吗？",
        onOk: () => {
          this.$api
            .delete(`${url}`)
            .then(r => {
              if (r.success) {
                this.$Message.success("删除成功");
                this.load();
              }
            })
            .catch(error => {
              this.$Message.error("删除失败");
            });
        }
      });
    },
    change(nodes, node) {
      // console.warn(node,nodes)
      this.node = {
        id: node.id,
        typeId: node.typeId,
        title: node.title,
        code: node.code
      };
      // this.names = [node.title]
      let cur = node;
      let titles = [];
      while (cur) {
        titles.push(cur.title);
        cur = cur.parent;
      }
      this.names = titles.reverse();
      this.load(node.id);
    },
    setRoot() {
      // this.load(0);
      this.loadTree();
      this.node = root;
    },
    async setColor(v, row, i) {
      let r = await api.setColor({ id: row.id, color: v });
      if (r.success) {
        this.$Message.success("颜色设置成功！");
        row.color = v;
      } else {
        this.$Message.error("颜色设置失败！");
        row.color = "";
      }
    },
    async load() {
      this.edit = -1;
      let r = await api.getChildren(this.node.id);
      this.data = r.result;
    },
    async loadTree() {
      let r = await api.getTree(this.node.id);
      if (r.success) {
        let items = r.result;
        var expand = this.expand;
        items = this.$u.toTree(
          items,
           null,
          (u,parent) => {
            u.parent = parent;
            u.title = u.name;
            u.expand = expand;
            u.contextmenu = true;
          },         
          "upId"
        );      
        this.tree = items;
      }
    },
    onDragDrop(a, b) {
      this.data.splice(b, 1, ...this.data.splice(a, 1, this.data[b]));
      let ids = [];
      this.data.map(u => {
        ids.push(u.id);
      });
      if (ids.length > 1) {
        api.setSort({ ids }).then(r => {
          if (!r.success) {
            this.$Message.error("排序失败");
            this.load();
          }
        });
      }
    },
    addNew() {
      this.edit = this.data.length;
      this.cur = {
        upId: this.node.id,
        name: "",
        code: "",
        color: "",
        status: 1,
        isStatic: 0,
        typeId: this.node.typeId + 1,
        priority: this.edit
      };
      this.data.push(this.cur);
    },
    remove() {
      this.edit = -1;
      // this.load(this.node.id)
      this.data.pop();
    },
    save() {
      if (this.cur.name == "") {
        this.$Message.error("名称不能为空");
        return;
      }
      if (this.cur.code == "") {
        this.$Message.error("值不能为空");
        return;
      }
      api.save(this.cur).then(r => {
        console.warn(r);
        if (r.success) {
          this.$Message.success("添加成功");
          this.load();
        }
      });
    }
  }
};
</script>
<style lang="less">
//框架页面layout用
.full {
  // height: calc(100vh - 120px);
  // margin-top: 45px;
  .menu {
    border: 1px solid #ddd;
    padding: 0 5px;
    .title {
      line-height: 45px;
      font-size: 14px;
      padding: 0 5px;
      border-bottom: #e4e6ed solid 1px;
      .fr {
        float: right;
        margin-top: 10px;
        cursor: pointer;
      }
      .fr:hover {
        color: #249e91;
      }
    }
    .tree {
      // height: calc(100% - 150px);
      overflow: auto;
    }
  }
  .content {
    background: white;
    border: 1px solid #ddd;
    padding: 10px;
    .auto {
      flex: 1;
      overflow: auto;
      position: relative;
      min-height: 600px;
    }
    .fly {
      position: relative;
      overflow: inherit;
    }
    .ivu-btn-small {
      padding: 0;
      background: red;
    }
  }
}
.ivu-color-picker-confirm {
  .ivu-input {
    width: 130px;
    height: 30px;
    float: left;
  }
  .ivu-btn-small {
    height: 30px !important;
  }
}
</style>

